<template>
  <div class="m-upload">
    <el-upload
      drag
      multiple
      :action="uploadImgUrl"
      :accept="'image/*,video/*'"
      :before-upload="handleBeforeUpload"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      :headers="headers"
      :file-list="fileList"
      list-type="picture-card"
      ref="imageUpload"
      :class="{ hide: fileList.length >= limit }"
    >
      <!-- 上传按钮 -->
      <el-icon class="avatar-uploader-icon" :size="50"><upload-filled /></el-icon>
      <template #file="{ file }">
        <video
          :src="file.url"
          controls="controls"
          v-if="file.type == 'video'"
          class="upload-video"
        ></video>
        <img class="upload-img" :src="file.url" alt="" v-if="file.type == 'image'" />
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <el-icon><zoom-in /></el-icon>
          </span>
          <span class="el-upload-list__item-delete" @click="handleRemove(file)">
            <el-icon><Delete /></el-icon>
          </span>
        </span>
      </template>
    </el-upload>
    <el-dialog v-model="dialogVisible" title="预览" width="800px" append-to-body>
      <video
        :src="dialogUrl.url"
        controls="controls"
        v-if="dialogUrl.type == 'video'"
        class="upload-video"
      ></video>
      <img
        :src="dialogUrl.url"
        style="display: block; max-width: 100%; margin: 0 auto"
        v-if="dialogUrl.type == 'image'"
      />
      <template #action></template>
    </el-dialog>
  </div>
</template>
<script setup>
import { getToken } from "@/utils/auth";
const props = defineProps({
  modelValue: [String, Object, Array],
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  videoSize: {
    type: Number,
    default: 30,
  },
  limit: {
    type: Number,
    default: 20,
  },
});

const { proxy } = getCurrentInstance();
const emit = defineEmits();
const number = ref(0);
const uploadList = ref([]);
const fileList = ref([]);
const headers = ref({ Authorization: "Bearer " + getToken() });
const dialogVisible = ref(false);
const dialogUrl = ref("");
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload"); // 上传的图片服务器地址
const videoType = [
  "video/mp4",
  "video/ogg",
  "video/flv",
  "video/avi",
  "video/wmv",
  "video/rmvb",
];
watchEffect(
  () => props.modelValue,
  (val) => {
    if (val) {
      console.log("val");
    }
  }
);
// 预览
function handlePictureCardPreview(file) {
  dialogUrl.value = file;
  dialogVisible.value = true;
}
// 删除文件
const handleRemove = (file) => {
  const fIndex = fileList.value.map((f) => f.name).indexOf(file.name);
  if (fIndex > -1 && uploadList.value.length === number.value) {
    fileList.value.splice(fIndex, 1);
    emit("update:modelValue", formatValue(fileList.value));
    return false;
  }
};
// 上传前loading加载
const handleBeforeUpload = (file) => {
  console.log(file);
  let isTrueFileType = false;
  // 检测文件类型： image、video
  if (file.type.indexOf("video") > -1 || file.type.indexOf("image") > -1) {
    isTrueFileType = true;
  }
  if (!isTrueFileType) {
    proxy.$modal.msgError(
      `文件格式不正确, 请上传${props.fileType.join("/")}图片格式文件!`
    );
    return false;
  }
  //   检测文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传头像图片大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy.$modal.loading("正在上传，请稍候...");
  number.value++;
};

// 上传成功的回调
const handleUploadSuccess = (res, file) => {
  if (res.code == 200) {
    uploadList.value.push({ type: res.type, name: res.fileName, url: res.url });
    uploadedSuccessfully();
  } else {
    number.value--;
    proxy.$modal.closeLoading();
    proxy.$modal.msgError(res.msg);
    proxy.$refs.imageUpload.handleRemove(file);
    uploadedSuccessfully();
  }
};

// 上传失败
const handleUploadError = () => {
  proxy.$modal.msgError("上传失败");
  proxy.$modal.closeLoading();
};
// 上传结束后的处理
const uploadedSuccessfully = () => {
  if (number.value > 0 && uploadList.value.length === number.value) {
    fileList.value = fileList.value
      .filter((f) => f.url !== undefined)
      .concat(uploadList.value);
    uploadList.value = [];
    number.value = 0;
    emit("update:modelValue", formatValue(fileList.value));
    proxy.$modal.closeLoading();
  }
};
// 对象转成指定字符串分隔
const listToString = (list, separator) => {
  let strs = "";
  separator = separator || ",";
  for (let i in list) {
    if (undefined !== list[i].url && list[i].url.indexOf("blob:") !== 0) {
      strs += list[i].url.replace(baseUrl, "") + separator;
    }
  }
  return strs != "" ? strs.substr(0, strs.length - 1) : "";
};
// 转换对象格式
const formatValue = (list) => {
  let _list = [];
  for (const i in list) {
    _list.push({
      type: list[i].type,
      name: list[i].name,
      url: list[i].url,
    });
  }
  return _list;
};
</script>

<style lang="scss" scoped>
.upload-video {
  width: 100%;
  height: 100%;
}
.upload-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
:deep(.hide .el-upload--picture-card) {
  display: none;
}
:deep(.el-upload-dragger) {
  border: none !important;
  background-color: none !important;
  .el-upload--picture-card i {
    font-size: 58px;
  }
}
</style>
